﻿using System;

namespace Aquarinum.WebSocekt.Core.Utils
{
    public static class DateTimeHelper
    {
        private static DateTime _baseTime = new DateTime(1970, 1, 1); //Unix起始时间

        /// <summary>
        ///     转换微信DateTime时间到C#时间
        /// </summary>
        /// <param name="unixTimestamp">微信DateTime</param>
        /// <returns></returns>
        public static DateTime GetDateTimeFromXml(long unixTimestamp)
        {
            return _baseTime.AddTicks((unixTimestamp + 8 * 60 * 60) * 10000000);
        }

        /// <summary>
        ///     计算目标日期UTC到1970年的时间差（unix基础时间）
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static double GetUtcSecondsFromBaseTime(this DateTime @this)
        {
            return Math.Round((@this.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                .TotalSeconds);
        }

        /// <summary>
        ///     获取UNIX时间戳
        /// </summary>
        /// <param name="dateTime">时间</param>
        /// <returns></returns>
        public static long GetUnixTimestamp(DateTime dateTime)
        {
            return (dateTime.Ticks - _baseTime.Ticks) / 10000000 - 8 * 60 * 60;
        }

        /// <summary>
        ///     获取UNIX时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetUnixTimestamp()
        {
            return (DateTime.Now.Ticks - _baseTime.Ticks) / 10000000 - 8 * 60 * 60;
        }
    }
}